package com.partners.controller.mp;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.partners.configure.wechatmp.WxMpConfiguration;
import com.partners.configure.wechatmp.WxMpProperties;
import com.partners.dao.basic.CustomerDao;
import com.partners.dao.basic.FansDao;
import com.partners.dao.basic.UserDao;
import com.partners.dao.bo.CustomerDO;
import com.partners.dao.bo.FansDO;
import com.partners.dao.bo.UserDO;
import com.partners.service.FansService;
import com.partners.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.net.URLEncoder;

/**
 * @author liangyongle
 * @date 2018-12-05
 */
@Controller
@RequestMapping("mp")
@Slf4j
public class WechatMpController {
    public final static String openid = "openId";
    @Resource
    private WxMpProperties wxMpProperties;

    @Resource
    private FansService fansService;

    @Resource
    private UserDao userDao;

    @Resource
    private CustomerDao customerDao;

    /*
     * 重定向地址
     * */
    @GetMapping("/authorize")
    public String authorize(@RequestParam("returnUrl") String returnUrl){
        //1.配置
        String baseUrl = wxMpProperties.getBaseUrl();
        String url = baseUrl+"/mp/userInfo";
        final WxMpService wxService = WxMpConfiguration.getMpServices().get(wxMpProperties.getBaseAppId());
        String redirectUrl = wxService.oauth2buildAuthorizationUrl(url, WxConsts.OAuth2Scope.SNSAPI_USERINFO, URLEncoder.encode(returnUrl));
        //2.跳转
        return "redirect:"+redirectUrl;
    }
    /*
     * 获取微信回调信息
     * */
    @GetMapping("/userInfo")
    public String userInfo(@RequestParam("code") String code,
                           @RequestParam("state") String redirectUrl,
                           @RequestParam(name="bind",required=false) Integer bind,
                           @RequestParam(name="customer_id",required=false) Integer customerId,
                           HttpSession session){

            String baseUrl = wxMpProperties.getBaseUrl();
            final WxMpService wxService = WxMpConfiguration.getMpServices().get(wxMpProperties.getBaseAppId());
            WxMpOAuth2AccessToken wxMpOAuth2AccessToken = new WxMpOAuth2AccessToken();
            try{
                wxMpOAuth2AccessToken =  wxService.oauth2getAccessToken(code);
            }catch(WxErrorException e){
                //System.out.println("【微信网页获取】"+e.getMessage());
            }
            String openId = wxMpOAuth2AccessToken.getOpenId();
            //0.0 如果是绑定的话，先绑定用户
            //1.获取openid 先判断是否有存在数据库记录
            Object fansInfo = fansService.getFansInfoByOpenId(openId);

            if(fansInfo != null){
                //已经关注
                String accessToken = wxMpOAuth2AccessToken.getAccessToken();
            }else{
                //绑定用户
                if(bind != null){
                    //绑定用户
                    UserDO userDO = userDao.selectByPrimaryKey(bind);
                    if(userDO != null){
                        log.info("openId::{}",userDO.getOpenid());
                        //1.判断该用户是否已经有绑定了，
                        if(userDO.getOpenid().equals("")){
                            UserDO user = new UserDO();
                            user.setId(bind);
                            user.setOpenid(openId);
                            userDao.updateByPrimaryKeySelective(user);
                        }
                    }
                }

                //绑定客户
                if(customerId != null){
                    //绑定客户的微信openid
                    CustomerDO customerDO = customerDao.selectDealByPrimaryKey(customerId);
                    if(customerDO != null){
                        log.info("openId::{}",customerDO.getOpenid());
                        //判断该用户是否已经绑定了微信
                        if(customerDO.getOpenid().equals("")){
                            CustomerDO customer = new CustomerDO();
                            customer.setId(customerId);
                            customer.setOpenid(openId);
                            customerDao.updateByPrimaryKeySelective(customer);

                        }
                    }
                }
                //没有关注
                redirectUrl = wxMpProperties.getSubscribeUrl();
            }

            //缓存openid信息
            session.setAttribute("openId", fansInfo);
            return "redirect:"+redirectUrl;

            //1.获取openid 先判断是否有存在数据库记录
            //2.有就查询是否已经关注
            //3.没有就查询是否已经关注
    }
}
